import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/record/items/data_left_list.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:ball_lion/module/record/player_logic.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

class PlayerPage extends StatefulWidget {
  const PlayerPage(this.leagueId, {super.key, required this.tag});

  final int leagueId;
  final String tag;

  @override
  State<PlayerPage> createState() => _PlayerPageState();
}

class _PlayerPageState extends State<PlayerPage>
    with AutomaticKeepAliveClientMixin {
  late PlayerLogic logic;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<PlayerLogic>(
      tag: widget.tag,
      initState: (state) {
        logic =
            Get.put(PlayerLogic(widget.leagueId, widget.tag), tag: widget.tag);
      },
      builder: (_) {
        return VisibilityDetector(
          key: Key(widget.tag),
          onVisibilityChanged: (VisibilityInfo info) {
            logic.visible = !info.visibleBounds.isEmpty;
          },
          child: LoadingWidget<bool>(
            isLoading: logic.struct == null,
            data: logic.struct?.length == 0,
            child: () => Row(
              children: [
                DataLeftList(logic.struct!.map((e) => e.value!).toList(),
                    logic.structIndex, ((p0) {
                  Utils.onEvent('zqsjpd_qyb',
                      params: {'zqsjpd_qyb': logic.struct![p0]});
                  logic.onSelectLeft(p0);
                })),
                _buildRightWidget(),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildRightWidget() {
    return Expanded(
        child: Container(
      color: Colours.white,
      child: Padding(
          padding: const EdgeInsets.only(left: 10, right: 4),
          child: LoadingWidget<bool>(
              isLoading: logic.header == null,
              data: logic.header?.length == 0,
              noData: const NoDataWidget(needScroll: true),
              child: () => Column(children: [
                    _buildHeaderWidget(),
                    Expanded(
                        child: EasyRefresh(
                            onRefresh: () async => logic.getData(),
                            controller: logic.refreshController,
                            child: LoadingWidget<int>(
                              isLoading: false,
                              data: logic.playerAll?.length,
                              noData: const NoDataWidget(needScroll: true),
                              child: () => MediaQuery.removePadding(
                                context: context,
                                removeTop: true,
                                child: ListView.separated(
                                  shrinkWrap: true,
                                  //physics: const NeverScrollableScrollPhysics(),
                                  itemCount: logic.playerAll?.length ?? 0,
                                  separatorBuilder: (context, index) =>
                                      const Divider(
                                          color: Colours.N3,
                                          height: 0.5,
                                          indent: 2,
                                          endIndent: 2),
                                  itemBuilder: (context, index) =>
                                      _buildPlayerWidget(index),
                                ),
                              ),
                            )))
                  ]))),
    ));
  }

  Widget _buildHeaderWidget() {
    return SizedBox(
      height: 38,
      child: Row(
        children: [
          const QsText('球员',
                  textAlign: TextAlign.center, color: Colours.N9, fontSize: 13)
              .sized(width: 34),
          const Spacer(),
          if (logic.channel.recordType == 0)
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                QsText(logic.header?.last ?? "",
                    textAlign: TextAlign.center,
                    color: Colours.grey66,
                    fontSize: 13),
              ],
            )
                .sized(width: 70)
                .tap(() => Get.dialog(const QsDialog.single('进球数包含点球'))),
          if (logic.channel.recordType == 1)
            ...logic.header!.map((e) => SizedBox(
                width: e == '球队' ? 60 : 42,
                child: QsText(
                  e,
                  textAlign: TextAlign.center,
                  color: Colours.grey99,
                  fontSize: 13,
                ))),
        ],
      ),
    );
  }

  Widget _buildPlayerWidget(int index) {
    final data = logic.playerAll![index];
    return SizedBox(
        height: 50,
        child: Row(children: [
          QsText(data.index ?? '', textAlign: TextAlign.center, fontSize: 13)
              .sized(width: 34),
          Stack(clipBehavior: Clip.none, children: [
            CachedNetworkImage(
                height: 32,
                width: 24,
                fit: BoxFit.cover,
                imageUrl: data.playerLogo!,
                placeholder: (context, url) => Styles.placeholderIcon(),
                errorWidget: (context, url, error) => Image.asset(
                    Utils.getImgPath('zq_placeholder.png'),
                    height: 32,
                    width: 24)),
            if (logic.channel.recordType == 0)
              Positioned(
                  bottom: -4,
                  right: -4,
                  child: CachedNetworkImage(
                      width: 16,
                      height: 16,
                      fit: BoxFit.cover,
                      imageUrl: data.teamLogo ?? "",
                      placeholder: (context, url) => Styles.placeholderIcon(),
                      errorWidget: (context, url, error) => Image.asset(
                            Utils.getImgPath('zq_placeholder.png'),
                            height: 16,
                            width: 16,
                          )))
          ]),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                QsText(
                  data.playerName ?? '',
                  fontSize: 13,
                  maxLines: 1,
                ),
                const SizedBox(height: 2),
                QsText(
                  logic.channel.recordType == 0
                      ? '${data.playerPosition} ${data.teamName}'
                      : '${data.playerPoints}分 ${data.playerRebounds}板 ${data.playerAssists}助',
                  color: Colours.grey66,
                  fontSize: 11,
                  maxLines: 1,
                )
              ],
            ),
          ),
          if (logic.channel.recordType == 1)
            ...List.generate(
                data.values!.length,
                (index) => SizedBox(
                    width: logic.header![index] == '球队' ? 60 : 42,
                    child: QsText(data.values![index],
                        textAlign: TextAlign.center, fontSize: 13))),
          if (logic.channel.recordType == 0)
            QsText(
              data.values?.last ?? '',
              textAlign: TextAlign.center,
              fontSize: 13,
            ).sized(width: 70)
        ]));
  }

  @override
  bool get wantKeepAlive => true;
}
